﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace IapApp.Manager
{
    public class DaoManager
    {
        private static volatile ISessionFactory _sessionFactory;

        private static readonly object Factorylock = new object();

        public ISession OpenSession<T>(string dbSchema, string appSetting)
        {
            lock (Factorylock)
            {
                if (_sessionFactory == null)
                {
                    var cfg = GetMySqlFluentConfiguration<T>(dbSchema, appSetting);
                    _sessionFactory = cfg.BuildSessionFactory();
                }
            }
            return _sessionFactory.OpenSession();
        }

        private static FluentConfiguration GetMySqlFluentConfiguration<T>(string dbSchema, string appSetting)
        {
            var cfg = Fluently.Configure()
                .Database(
                    MySQLConfiguration.Standard
                        .DefaultSchema(dbSchema)
                        .ConnectionString(c => c.FromAppSetting(appSetting))
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<T>());
            return cfg;
        }

        private static FluentConfiguration GetSqlServerFluentConfiguration<T>(string dbSchema, string appSetting)
        {
            var cfg = Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2008
                        .DefaultSchema(dbSchema)
                        .ConnectionString(c => c.FromAppSetting(appSetting))
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<T>());
            return cfg;
        }
    }
}
